package com.afdor.rws.event.driven.support.channel.consumer.handler;


import com.afdor.rws.core.exception.BusinessException;
import com.afdor.rws.event.driven.api.channel.consumer.EventConsumer;
import com.afdor.rws.event.driven.api.channel.consumer.handler.EventHandler;
import com.afdor.rws.event.driven.entities.Event;
import lombok.NonNull;

/**
 * 事件处理器代理对象
 *
 * @author 悭梵
 * @date Created in 2018-12-05 16:09
 */
public class ProxyEventHandler implements EventHandler {
    /**
     * 原始事件处理器对象
     */
    private final EventHandler targetEventHandler;
    /**
     * 原始事件处理器对象
     */
    private final EventConsumer eventConsumer;

    public ProxyEventHandler(@NonNull EventConsumer eventConsumer, @NonNull EventHandler eventHandler) {
        this.eventConsumer = eventConsumer;
        this.targetEventHandler = eventHandler;
    }

    @Override
    public Object handler(final Event event) {
        if (event != null) {
            event.setEventBus(this.eventConsumer.getEventBus());
            try {
                event.setStatus(Event.Status.EXECUTING);
                return this.targetEventHandler.handler(event);
            } catch (Exception e) {
                if (event.getRetryCount() <= this.eventConsumer.getConfig().getMaxRetryCount()) {
                    event.setStatus(Event.Status.FAILURED);
                } else {
                    event.setStatus(Event.Status.TERMINATED);
                }
                if (e instanceof RuntimeException) {
                    throw (RuntimeException) e;
                }
                throw new BusinessException("事件处理异常", e);
            }
        }
        return null;
    }
}
